package edu.pw.treegrid.server.web;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import xalan.smartgwt.criteria.Criteria;
import xalan.smartgwt.criteria.CriteriaSQLGenerator;
import edu.pw.treegrid.server.filter.OperatorType;
import edu.pw.treegrid.server.filter.SimpleFilter;
import edu.pw.treegrid.server.query.ColumnNode;
import edu.pw.treegrid.server.query.QueryTree;
import edu.pw.treegrid.server.reportmodel.ReportColumn;

public class SmartGWTFilter extends SimpleFilter {
	
	class Generator extends CriteriaSQLGenerator {
		private Map<String, String> reportColumnToColumnAlias = new HashMap<String, String>();
		
		private Generator(QueryTree queryTree) {
			for(Entry<ReportColumn, Set<ColumnNode>> e: queryTree.getReportColumnToColumNodes().entrySet()) {
				ColumnNode columnNode = null;
				for(ColumnNode c: e.getValue()) {
					if((e.getValue().size() == 2 && !c.isIdColumn()) || e.getValue().size() == 1) {
						columnNode = c;
					}
				}
				reportColumnToColumnAlias.put(e.getKey().getName(), columnNode.getBaseExpressionString());
			}
		}

		@Override
		protected String transformFieldName(String fieldName) {
			return reportColumnToColumnAlias.get(fieldName);
		}
		
	}
	
	@Override
	public void generateWhere(QueryTree queryTree, StringBuilder sb) {
		Generator generator = new Generator(queryTree);
		sb.append(generator.generate(criteria));
		for(Object o: generator.getParametersMap().values()) {
			queryTree.addParameter(o);
		}
	}

	public SmartGWTFilter(Criteria criteria) {
		super();
		this.criteria = criteria;
	}

	private Criteria criteria;

	@Override
	public OperatorType getOperatorType() {
		// TODO Auto-generated method stub
		return null;
	}
	
}
